var currentEle;
(function($){

    $.fn.quiggleDynamicJobAdd = function (templateBlock, placeHolder, indexBlock){
        $(this).click(function(){
//            alert("add address click " + templateBlock);
            var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
//            alert("index " + index);
            var templateClone = template.clone();
//            alert(templateClone.html());
            templateClone.html(templateClone.html().replace(/{index}/g, index));
            templateClone.attr('id', template.attr('id') + '-' + index)
//            templateClone.removeClass('template');
			if($(placeHolder).attr("id")=="job-placeholder")
			{
				
				 templateClone.html(templateClone.html().replace(/mandatoryfield-temp/g, "mandatoryfield"));
				
			}
            templateClone.insertAfter($(placeHolder));
			
//            alert(templateClone.html());
            indexField.text(index + 1);
            templateClone.bindJobEvents();
           // var statusField = templateClone.find("[name='job.statusId']");
		   var statusField =templateClone.find("[name='job.agencyInitial']"); 
//            alert(statusField.attr("name"));
            statusField.focus();
		        });
    };

	retflag=false;
	
	$.fn.QGLCustomValidator=function(validatestring,submit,form){
	
	var Requirederrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>This Field is Required.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){retflag=requiredfieldvalidtion($(form).find(this).val());
	if (!retflag){$(form).find(this).before(Requirederrorstr);}
	else{$(form).find(this).parent().find(".ketchup-errorPar").remove();}
	}    
	$(this).live("blur",function(){
	retflag=requiredfieldvalidtion($(this).val());
	if (!retflag){$(this).before(Requirederrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});
	
	return retflag;
	}; 	
	$.fn.QGLCustomValidatorNum=function(validatestring,submit,form){
	
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){retflag=numberfieldvalidtion($(form).find(this).val());
	if (!retflag){$(form).find(this).before(numbererrorstr);}
	else{$(form).find(this).parent().find(".ketchup-errorPar").remove();}
	}    
	$(this).live("blur",function(){
	retflag=numberfieldvalidtion($(this).val());
		if (!retflag){$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	}; 
	
    $.fn.quiggleJobAutoComplete = function(dataSource, idField, dialogForm){
        $( this ).autocomplete({
            minLength: 0,
//                source: projects,
            source: dataSource,
            focus: function( event, ui ) {
//                    $( "#project" ).val( ui.item.label );
                $(this).val( ui.item.initial);
                return false;
            },
            select: function( event, ui ) {
			 
//                    $( "#project" ).val( ui.item.label );
                $(this).val( ui.item.initial);
//                    $( "#project-id" ).val( ui.item.value );
//                alert("change " + ui.item.id);
                $( this ).parent().find(idField).val( ui.item.id );
//                    $( "#project-description" ).html( ui.item.desc );
//                    $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );

                return false;
            },
            change: function(event, ui){
						 

			//ui.item.id=1;
			//ui.item.initial="yazu"
			var textval=$.trim($(this).val()).toLowerCase();
			
			if(textval == "")
				return false;
			
			var flag=true;
			for (var i = 0; i < dataSource.length; i++) {
			  if ($.trim(dataSource[i].initial).toLowerCase() == textval) {

						flag=false;
			    			$( this ).parent().find(idField).val(dataSource[i].id);
					}
				  }
				  
					  
			 
                if(ui.item === null && flag){
//                       alert('ui is null');
                    $(this).parent().find(idField).val('');
                    $(dialogForm).find(".block-id").val($(this).parent().attr("id"));
                    $(dialogForm).find(".initial").val($(this).val());
                    $( dialogForm ).dialog("open");
					currentEle=idField;
                }
                return false;
            }
        })
            .data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.initial + " (" +item.firstName + item.lastName + ")" + "</a>" )
                .appendTo( ul );
        };

    };

    $.fn.bindJobEvents = function(){

        $(this).find('.edit-job').each(function(){

            $(this).click(function(){
            	 $(this).closest(".job-row").find('.view').hide();
                 $(this).closest(".job-row").find('.edit').show();
                 $(this).closest(".job-row").find("[name='job.statusId']").focus();
				 $(this).closest(".job-row").find(':input[value=""].edit:first').focus();
            })
        });

        $(this).find('.cancel-edit').each(function(){
            $(this).click(function(){
            	 $(this).closest(".job-row").find('.edit').hide();
                 $(this).closest(".job-row").find('.view').show();
				 $(this).closest(".job-row").find(".ketchup-errorPar").remove();
            })
        });


        $(this).find(".date-picker").each(function(){
            $(this).removeClass('hasDatepicker');
            $(this).datepicker();
        });

        $(this).find(".agency-initial").each(function(){
            $(this).quiggleJobAutoComplete(agencies, '.agency-id', "#agency-form");
        });

        $(this).find(".scopist-initial").each(function(){
            $(this).quiggleJobAutoComplete(scopists, '.scopist-id', "#scopist-form");
        });

        $(this).find(".proofer-initial").each(function(){
            $(this).quiggleJobAutoComplete(proofers, '.proofer-id',"#proofer-form");
        });



    };

})(jQuery);
$('.estimatePages').live("change",function(){
var jobId = $(this).closest(".job-row").find('.jobId').val();
var index = $(this).closest(".job-row").find('.newjobIndex').val();
$("#estimatePages-form").dialog({
height: 350,
width: 600,
modal: true,
title:"MY HOURS TO PERFORM TASK",
hide: 'fold',
show: 'blind',
buttons: {

"Save":function(){
saveAdminstrativeHoursInJob(actualUserId,jobId,index);

},
"Cancel": function() {
$('.estimatePages').closest("div").next().find("input:visible").focus();
$(this).dialog('close');
}
},

});
$('.ui-icon').click(function(){
		
$('.estimatePages').closest("div").next().find("input:visible").focus();
});
callAjaxToDisplayAdminstrativeHours(actualUserId,jobId,"old");
});
function Decinumberfieldvalidtion(eleVal){
			var flag=true;
			if(isNaN(eleVal))
				flag =false;
			return flag;
	}
function requiredfieldvalidtion(eleVal){
		var flag=false;
		if(eleVal=="")
			flag=false;
		else
			flag=true;
			
		return flag;
		}

function numberfieldvalidtion(eleVal){
		var flag=true;
		if(isNaN(eleVal))
			flag = false;
		else if(eleVal % 1 != 0)
			flag = false;
		return flag;	
		}

$(document).ready(function(){	
	   $(".hrstodoname").live("click",function(){
		   $('.selectedTask').each(function() {
			   $(this).removeClass("selectedTask");
			});
		   $(this).closest("div").addClass("selectedTask");
	   });
					  
	$("#instructionsHideLinkForQGL").live("click",function(){

	  $("#contentInsForQGL").hide();
	  $("#instrutionsSpanForQGL").html("<a title='click here to show the instructions' id='instructionsShowLinkForQGL' style='background:#E3F2FF;' href='javascript:{}'><img  id='instructionsDownarrowimg' src='images/downarrow.png' width='10' height='9' alt='Hide' /></a>");
	});
						

	$("#instructionsShowLinkForQGL").live("click",function(){
	  $("#contentInsForQGL").show();
	  $("#instrutionsSpanForQGL").html("<a title='click here to hide the instructions' id='instructionsHideLinkForQGL' style='background:#E3F2FF;' href='javascript:{}'><img  id='instructionsuparrowimg' src='images/uparrow.png' width='10' height='9' alt='Hide' /></a>");

	});
	
	$('.job-row').live("keypress",function(){		
		isFormFieldChanged = true;
		isPendingChanged = true;
		
	});
	
	$('.date-picker').live("click",function(){		
		isFormFieldChanged = true;
		isPendingChanged = true;
		
	});
//navigating without saving
var warnMessage = "You have unsaved changes on this page!";


    $('input:not(:button,:submit)').live("keypress", function () {
        window.onbeforeunload = function () {
		 if (warnMessage != null) return warnMessage;
        }
    });
	
	
    $('input:submit').click(function(e) {
		window.onbeforeunload = null;
        warnMessage = null;
    });


//end of navigating without saving

	//tooltips work start
			/* $(".t-tip").each(function(){
				var spantag="<span class='toolTip-cust'><span class='toolTip-caption'>"+$(this).attr("title")+"</span></span>"
				//$(this).wrap("");
				$(this).before(spantag);    
				$(this).removeAttr("title");
			  });
			
			$(".t-tip").live("focusin mouseover",function(){
		      $(this).closest("div").find(".toolTip-cust .toolTip-caption").show("fast");
			  if($(".agency,.scopist,.proofer").find(this).not(":hidden").hasClass("view")){
			   $(this).closest("div").find(".toolTip-cust:eq(0) .toolTip-caption").show("fast");
			    $(this).closest("div").find(".toolTip-cust:eq(1) .toolTip-caption").hide();
			  }
			  else if($(".agency,.scopist,.proofer").find(this).not(":hidden").hasClass("edit")){
			  $(this).closest("div").find(".toolTip-cust:eq(1) .toolTip-caption").show("fast");
			    $(this).closest("div").find(".toolTip-cust:eq(0) .toolTip-caption").hide();}
		    });
			
			$(".t-tip").live("focusout mouseout",function(){			
			      $(this).closest("div").find(".toolTip-cust .toolTip-caption").hide("fast");
            });
			*/
			
	//tooltip work ended
	
$(".mandatoryfield").QGLCustomValidator("required",false);
$(".numberVal").QGLCustomValidatorNum("number",false);

$(".agency-initial").live("focus", function(){
	if(($(this).prev().attr("class")=="ketchup-errorPar") && ($(this).prev().find(".ketchup-error ul li")!=""))
		$(this).parent().find(".ketchup-errorPar").hide();	
});

$(".agency-initial").live("blur", function(){
	if(($(this).prev().attr("class")=="ketchup-errorPar") && ($(this).prev().find(".ketchup-error ul li")!=""))
		$(this).parent().find(".ketchup-errorPar").show();	
});


$(".initial").blur(function(){


	var initial=$(this).val();
	var initials=initial.toUpperCase();
	
	var upperCasedAgencyArray = new Array();
	var upperCasedScopistArray = new Array();
	var upperCasedProoferArray = new Array();
	
	$.each(agyIntlsArray, function(index, item) {
    upperCasedAgencyArray[index] = item.toUpperCase();
     });
	 $.each(scpIntlsArray, function(index, item) {
    upperCasedScopistArray[index] = item.toUpperCase();
     });
	 $.each(prfIntlsArray, function(index, item) {
    upperCasedProoferArray[index] = item.toUpperCase();
     });
	
	//var upperCasedScopistArray = $.map(scpIntlsArray, String.toUpperCase);
	//var upperCasedProoferArray = $.map(prfIntlsArray, String.toUpperCase);
	if($(this).attr("id")=="agency-initial"){
		if($.inArray(initials, upperCasedAgencyArray)!=-1){			
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Ok");
			$(this).parent().next().find("input").val(initials);
			$(this).parent().next().css("display", "none");
			$(this).parent().parent().next().css("display", "block");
		}
		else{
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create an agency");
			$(this).parent().next().css("display", "block");
			$(this).parent().parent().next().css("display", "none");
			$('#agency-name').val('');
			}
	}
	else if($(this).attr("id")=="scopist-initial"){
		if($.inArray(initials, upperCasedScopistArray)!=-1){			
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Ok");
			$(this).parent().next().find("input").val(initials);
			$(this).parent().next().css("display", "none");
			$(this).parent().parent().next().css("display", "block");
		}
		else{
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a scopist");
			$(this).parent().next().css("display", "block");
			$(this).parent().parent().next().css("display", "none");
			$('#scopist-name').val('');
			}
	}
	else if($(this).attr("id")=="proofer-initial"){
		if($.inArray(initials, upperCasedProoferArray)!=-1){			
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Ok");
			$(this).parent().next().find("input").val(initials);
			$(this).parent().next().css("display", "none");
			$(this).parent().parent().next().css("display", "block");
		}
		else{
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a proofer");
			$(this).parent().next().css("display", "block");
			$(this).parent().parent().next().css("display", "none");
			$('#proofer-name').val('');
			}
	}
	
});

$('.job-row').live("submit",function(){
    
$(".mandatoryfield").QGLCustomValidator("required",true,this);
if(retflag)
$(".numberVal").QGLCustomValidatorNum("number",true,this);

//alert(retflag);
 flag=retflag;
 if(flag)  warnMessage = null;
	return flag;
	
});

$(".ui-dialog-buttonset").live("click",function(){

	$(currentEle).closest("div").next().find("input:visible").focus();

});

$(".date-picker").live("change",function(){
//alert("TEST");
var val=$(this).val();
if(val.length>0)
$(this).closest("div").next().find("input:visible").focus();
});

/** HIGHLIGHT  COLUMNS **/

$(".job-column").live("focusin",function(){
var colindex=$(this).index();
var rowindex=$(this).closest(".job-row").index();
$(this).addClass("higlightclass");
$(".job-row:eq(0)").find(".job-column:eq("+colindex+")").addClass("higlightclass");
});

$(".job-column").live("focusout",function(){
var colindex=$(this).index();
var rowindex=$(this).closest(".job-row").index();
$(this).removeClass("higlightclass");
var parentwin=$(".job-row:eq(0)").find(".job-column:eq("+colindex+")").removeClass("higlightclass");
});
	
/** HIGHLIGHT END ***/	


    $(this).bindJobEvents();

    $("#add-job").quiggleDynamicJobAdd("#job-template", "#job-placeholder", "#job-index");
	/* number validations 
	$('.estPageVal').attr("pattern","^[0-9]+$");*/

	/*$(".mandatoryfield").live("focus",function(){
	$(this).attr("data-validate","validate(required)");});*/
	/* $(".mandatoryfield").attr("data-validate","validate(required)");
	$(".emailval").customValidator("validate(email)");
	$(".urlinput").customValidator("validate(url)");
	$(".numberVal").customValidator("validate(price)");*/
		
		//$("form").ketchup();
    
    
	$('.close').live("click",function(){
	   $('#successDiv').hide();
	   	
	});
});




$(function() {
    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
//		$( "#dialog:ui-dialog" ).dialog( "destroy" );

    var name = $( "#name" ),
        email = $( "#email" ),
        password = $( "#password" ),
        allFields = $( [] ).add( name ).add( email ).add( password ),
        tips = $( ".validateTips" );

    var agencyInitial = $("#agency-initial"),
        agencyName = $("#agency-name"),
        allAgencyFields = $([]).add(agencyInitial).add(agencyName),
        agencyTips = $(".agency-validation-tips");


    function updateTips( t ) {
        tips
            .text( t )
            .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }

    function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass( "ui-state-error" );
            updateTips( "Length of " + n + " must be between " +
                min + " and " + max + "." );
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }

    $( "#agency-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create an agency": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );
				var eFlag = false;
				var str = '';

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    agency.find('.agency-id').val('0');
                    agency.find('.agency-initial').val($("#agency-initial").val())
                    agency.find('.agency-name').val($("#agency-name").val())
                    agency.find('.agency-initial').focus();
					
						
					if($.trim($("#agency-initial").val()) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim($("#agency-name").val()) == "")
					{
						str +='Name is Required.';
						eFlag = true;
					}
					$("#agency-form-errorMsgDiv").html(str);
					if(eFlag)
						return;
					//callAjaxToCheckInitials($("#agency-initial").val(), 2, agency);
                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
            	 var block = $(this).find('.block-id').val();
                 var agency = $('#' + block);
            	
            		agency.find('.agency-initial').val("");
            		agency.find('.date-picker').blur();
            		agency.find('.agency-initial').focus();
            	
            		
                $( this ).dialog( "close" );
            }
        },
     
        close: function(event, ui) {
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
            if ( event.originalEvent && 
                    $(event.originalEvent.target).closest(".ui-dialog-titlebar-close").length ) {
            	var block = $(this).find('.block-id').val();
        		var agency = $('#' + block);       	
        		agency.find('.agency-initial').val("");
        		agency.find('.date-picker').blur();
        		agency.find('.agency-initial').focus();
            }
			
			$(this).closest(".ui-dialog").find(".ui-button:first span").text("Create an agency");
			$(this).find("#agency-name").val("");
			$(this).find("#agency-name").parent().css("display", "block");
			$(this).find("#agency-name").parent().parent().next().css("display", "none");
			
        }
    });

    $( "#scopist-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create a scopist": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );
				var eFlag = false;
				var str = '';

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    agency.find('.scopist-id').val('0');
                    agency.find('.scopist-initial').val($("#scopist-initial").val())
                    agency.find('.scopist-name').val($("#scopist-name").val())
                    agency.find('.scopist-initial').focus();
					if($.trim($("#scopist-initial").val()) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim($("#scopist-name").val()) == "")
					{
						str +='Name is Required.';
						eFlag = true;
					}
					$("#scopist-form-errorMsgDiv").html(str);
					if(eFlag)
						return;
					
					
					//callAjaxToCheckInitials($("#scopist-initial").val(), 3, agency);
                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
            	var block = $(this).find('.block-id').val();
                 var agency = $('#' + block);
            	
            		agency.find('.scopist-initial').val("");
            		agency.find('input').blur();

            		agency.find('.scopist-initial').focus();
            	
            	
                $( this ).dialog( "close" );
            }
        },
        close: function(event, ui) {
        	if ( event.originalEvent && 
                      $(event.originalEvent.target).closest(".ui-dialog-titlebar-close").length ) {
              	var block = $(this).find('.block-id').val();
          		var agency = $('#' + block);       	
          		agency.find('.scopist-initial').val("");
        		agency.find('input').blur();
        		agency.find('.scopist-initial').focus();
            }
        	
        	allAgencyFields.val( "" ).removeClass( "ui-state-error" );
            $(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a scopist");
            $(this).find("#scopist-name").val("");
			$(this).find("#scopist-name").parent().css("display", "block");
			$(this).find("#scopist-name").parent().parent().next().css("display", "none");
        }
    });

    $( "#proofer-form" ).dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Create a proofer": function() {
                var bValid = true;
                allAgencyFields.removeClass( "ui-state-error" );
				var eFlag = false;
				var str = '';

//                bValid = bValid && checkLength( name, "username", 3, 16 );
//					bValid = bValid && checkLength( email, "email", 6, 80 );
//					bValid = bValid && checkLength( password, "password", 5, 16 );

//					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
//					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
//					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

                if ( bValid ) {
                    /*
                     $( "#users tbody" ).append( "<tr>" +
                     "<td>" + name.val() + "</td>" +
                     "<td>" + email.val() + "</td>" +
                     "<td>" + password.val() + "</td>" +
                     "</tr>" );
                     */
                    var block = $(this).find('.block-id').val();
                    var agency = $('#' + block);

                    agency.find('.proofer-id').val('0');
                    agency.find('.proofer-initial').val($("#proofer-initial").val())
                    agency.find('.proofer-name').val($("#proofer-name").val())
                    agency.find('.proofer-initial').focus();

					if($.trim($("#proofer-initial").val()) == "")
					{
						str +='Initial is Required.';
						eFlag = true;
					}
					if($.trim($("#proofer-name").val()) == "")
					{
						str +='Name is Required.';
						eFlag = true;
					}
					$("#proofer-form-errorMsgDiv").html(str);
					if(eFlag)
						return;
					//callAjaxToCheckInitials($("#proofer-initial").val(), 4, agency);

                    $( this ).dialog( "close" );
                }
            },
            Cancel: function() {
            	 var block = $(this).find('.block-id').val();
                 var agency = $('#' + block);
            	
            		agency.find('.proofer-initial').val("");
            		agency.find('input').blur();
                	agency.find('.proofer-initial').focus();	
            		
                $( this ).dialog( "close" );
            }
        },
        close: function(event, ui) {
        	if ( event.originalEvent && 
                    $(event.originalEvent.target).closest(".ui-dialog-titlebar-close").length ) {
            	var block = $(this).find('.block-id').val();
        		var agency = $('#' + block);       	
        		agency.find('.proofer-initial').val("");
        		agency.find('input').blur();
            	agency.find('.proofer-initial').focus();	
	        }
            allAgencyFields.val( "" ).removeClass( "ui-state-error" );
            $(this).closest(".ui-dialog").find(".ui-button:first span").text("Create a proofer");
            $(this).find("#proofer-name").val("");
			$(this).find("#proofer-name").parent().css("display", "block");
			$(this).find("#proofer-name").parent().parent().next().css("display", "none");
        }
    });

});

function callAjaxToCheckInitials(initials, userType, agency){	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?checkIfInitialsExist',
		  dataType: 'json',
		  data: {initials:initials, userType:userType},
			 
		  success: function(result){
			  if(result==-1){
				 showError(userType, agency);
			  }            
		  },
		  error:function() { 
			  
		  }
 	});	
	
}
function decimalNumbervalidtion(eleVal){
			var flag=true;
			if(isNaN(eleVal))
				flag =false;
			return flag;
		}
function caluculateAllHours(jobid,index){
	  var estimatedPages = 0;
	  var scopistId = 0;
	  var prooferId = 0;
	  if($.trim($("#estpages-"+index).val()).length > 0 && $("#estpages-"+index).val() > 0)
		  estimatedPages = $("#estpages-"+index).val();
	  
	  if($.trim($("#scopist-id-"+index).val()).length > 0 && $("#scopist-id-"+index).val() > 0)
		  scopistId = $("#scopist-id-"+index).val();
	  
	  if($.trim($("#proofer-id-"+index).val()).length > 0 && $("#proofer-id-"+index).val() > 0)
		  prooferId = $("#proofer-id-"+index).val();
	  
	  calculateHrsToDoAndTotalHrs(estimatedPages,jobid,scopistId,prooferId,index);
}

function calculateHrsToDoAndTotalHrs(estimatedPages,jobId,scopistId,prooferId,index){
	   $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?calculateHrsToDoAndTotalHrs',//name of action?name of method in action
		  dataType: 'json',
		  data: {jobId:jobId,estPages:estimatedPages,scopistId:scopistId,prooferId:prooferId},
			 
		  success: function(result){
        if(result != null){
      	  
      	  $("#totalhrs-"+index).val(result.toDoHours);
      	  
        }
		 },
		  error:function() { 
			  
		  }
	});
	
}

function saveAdminstrativeHoursInJob(actualUserId,jobId,index){
	var str ='';	 
	var flag = true;
	var errmsg = $('#errorDiv');
	var skillAdminHrs = $('#skillAdminHrsId').val();
	
	var defaultSkillType = $('input[name=hrstodoname]:radio:checked').val();
	var flag= decimalNumbervalidtion(skillAdminHrs);
	if(!flag)
	{
		
		$('#errorDiv').text("Enter Numeric Value.").addClass( "ui-state-highlight").css({"background":"#FFE4DD", "margin-bottom": "5px", "width": "250px", "padding": "3px", "font-family": "verdana","font-weight": "bold","color":"#000"});
    
		
		return;
	}
	if(flag)
		  {
$("#errorDiv").empty();
			$("#errorDiv").removeClass("errdiv");
 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?saveAdminstrativeHoursInJob',
		  dataType: 'json',
		  data: {userId:actualUserId, jobId:jobId,skillAdminHrs:skillAdminHrs,defaultSkillType:defaultSkillType},
			 
		  success: function(result){
			 
					$('#errorDiv').text("Administrative Hours saved Successfully").addClass("alert alert-success");
			$('.estimatePages').closest("div").next().find("input:visible").focus();

					setTimeout("closewindow()",2000);
				  caluculateAllHours(jobId,index);
				 
			          
		  },
		  error:function() { 
			  
		  }
 	});	
		  }
}

function closewindow()
{
	$("#estimatePages-form").dialog("destroy");
}

function callAjaxToDisplayAdminstrativeHours(actualUserId,jobId,type,index){	
	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		  type:'POST',
		  url: 'qgl-log-pending.action?checkIfHoursToPerFormExist',
		  dataType: 'json',
		  data: {userId:actualUserId, jobId:jobId},
			 
		  success: function(result){
			  if(result!=null){
				 //showError(userType, agency);
				//quiggleJobAutoComplete(result, '.est-id',"#estimatePages-form");
				showDialogue(result,type,index);
			  }            
		  },
		  error:function() { 
			  
		  }
 	});	
	
}


function saveHrsToDoForNewJobs(index){
		$("#estimatePages-form-new").dialog({
		height: 350,
		width: 600,
		modal: true,
		title:"MY HOURS TO PERFORM TASK",
		hide: 'fold',
		show: 'blind',
		buttons: {

		"Save":function(){
		
		populateAdminstrativeHoursInJob(index);
		//$('.newEstimatePages').closest("div").next().find("input:visible").focus();
		},
		"Cancel": function() {
			
		currentEle = '.newEstimatePages';
		$(this).dialog('close');
		}
		},

		});
		$('.ui-icon').click(function(){
		
$('.newEstimatePages').closest("div").next().find("input:visible").focus();
});
		callAjaxToDisplayAdminstrativeHours(actualUserId,0,"new",index);
}

function populateAdminstrativeHoursInJob(index){
	
	var skillAdminHrs = $('#skillAdminHrsId').val();
	var defaultSkillType = $('input[name=hrstodoname]:radio:checked').val();
	var flag= decimalNumbervalidtion(skillAdminHrs);
	if(!flag)
	{
		
		$('#errorDiv').text("Enter Numeric Value.").addClass( "ui-state-highlight").css({"background":"#FFE4DD", "margin-bottom": "5px", "width": "250px", "padding": "3px", "font-family": "verdana","font-weight": "bold","color":"#000"});
    
		
		return;
	}
	$("#skillType-"+index).val(defaultSkillType);
	$("#skillAdminHrs-"+index).val(skillAdminHrs);
	caluculateMyHoursTODO(index);
	$('#errorDiv').text("Administrative Hours saved Successfully").addClass("alert alert-success");
	//$('.newEstimatePages').closest("div").next().find("input:visible").focus();
	currentEle = '.newEstimatePages';
	setTimeout("closeNewWindow()",2000);
}

function closeNewWindow(){
	//$('.newEstimatePages').closest("div").next().find("input:visible").focus();
	$("#estimatePages-form-new").dialog("destroy");
	
}

function showDialogue(result,type,index)
{

	  $("#estimatePages-formInnerDiv").html("");
	  $("#estimatePages-formInnerDiv-new").html("");
	var str='';
	str +='<div id="errorDiv"></div>';
	 str+=' <fieldset>'
     str+=' <div style="font-size: 14px;font-family: verdana;">';
     str+='<input type="hidden" name="block-id" class="block-id" value=""/>';
     for(var i=0;i<result.length;i++)
	{ 
    	 var skilltype =  result[i].defaultSkillType;
    	 var administrativeHours =  result[i].administrativeHours;
    	if(type != "old"){ 
    	    var newSkillType = $("#skillType-"+index).val();
    	 
    	    var newSelectedSkillAdminHrs = $("#skillAdminHrs-"+index).val();
    	 
    	    if($.trim(newSkillType).length > 0 && newSkillType > 0){
    		  skilltype = parseInt(newSkillType,10);
    	    }
    	 
    	    if($.trim(newSelectedSkillAdminHrs).length > 0 && newSelectedSkillAdminHrs > 0){
    		  administrativeHours = parseFloat(newSelectedSkillAdminHrs,10);
    	    }
    	  } 
		 if(skilltype == 1)
		{
			 str +='<div id="regularDefaultDiv" class="selectedTask">';
    str+='<input type="radio" name="hrstodoname" class="hrstodoname"  id="regularDefault" value="1" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;" checked="true"/>';
		}
		else
		{
			 str +='<div id="regularDefaultDiv">';
			str+='<input type="radio" name="hrstodoname" class="hrstodoname"  id="regularDefault" value="1" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}

	str+=' <span class="label">Regular</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].regularScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].regularProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br>';
	 if(skilltype == 2)
		{
		  str +='<div id="denseDefaultDiv" class="selectedTask">';
		 str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="denseDefault" value="2" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;" checked="true"/>';
		}
		else
		{
			 str +='<div id="denseDefaultDiv">';
str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="denseDefault" value="2" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}
	str+=' <span class="label">Dense</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">';
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].denseScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].denseProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br>';
	
	 if(skilltype == 3)
		{
		str +='<div id="easyDefaultDiv" class="selectedTask">';
    str+=' <input type="radio" name="hrstodoname" class="hrstodoname"  id="easyDefault" value="3" class="initial text ui-widget-content ui-corner-all" style="margin-left:4px;" checked="true"/>';
	 
		}
		else
		{
			 str +='<div id="easyDefaultDiv">';
	str+=' <input type="radio" class="hrstodoname" name="hrstodoname" id="easyDefault" value="3" class="initial text ui-widget-content ui-corner-all popup" style="margin-left:4px;"/>';
		}
	str+=' <span class="label">Easy</span>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Scope</span>';
	str+='<span style="padding-left:5px;">'+result[i].easyScopeHours+'</span>';
	str +='</div>';
	str +='<div style="display: inline-table;margin-left: 10px;width: 100px;">'
	str +='<span>Proof</span>';
	str+='<span style="padding-left:5px;">'+result[i].easyProofHours+'</span>';
	str +='</div>';
	str +='</div>';
	str +='<br><br>';
	str +='<div style="font-size:11px;">(To change the values of default fields above, please do so from your Profile page.)</div><br>';
	str +='<div style="font-size:12px;">';
	str+=' <label for="skillAdminHrs">FOR THIS PARTICULAR JOB: Administrative Hours</label>';
	str+='<input type="text" maxlength="10" id="skillAdminHrsId" value="'+administrativeHours+'" name="skillAdminHr" style="width:60px;height:18px;border-radius: 3px 3px 3px 3px;border:1px solid #ccc;margin-left:1px;padding:3px;display: inline-table;" class="decimalnumberVal skillAdminHrs"/>';
	str +='</div>';
	}
	str+='</div>';
    str+=' </fieldset>';
    if(type == "old")
  	  $("#estimatePages-formInnerDiv").html(str);
      else
  	  $("#estimatePages-formInnerDiv-new").html(str);
      
}

